package com.jzsm.modules.sender.senderService.impl.dingtalk;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.jzsm.modules.sender.enums.ChannelTypeEnum;
import com.jzsm.common.annotation.Channel;
import com.jzsm.common.utils.AssertUtils;
import com.jzsm.modules.sender.pojo.PushChannelAccount;
import com.jzsm.modules.sender.bo.accountConfig.DingtalkAppAccountConfigBo;
import com.jzsm.modules.sender.enums.DomainNameEnum;
import com.jzsm.modules.sender.senderService.AbstractMessageSender;
import com.jzsm.modules.sender.senderService.impl.dingtalk.utils.DingtalkUtils;
import com.taobao.api.ApiException;
import lombok.AccessLevel;
import lombok.experimental.FieldDefaults;
import org.springframework.stereotype.Component;

/**
 * 钉钉应用 渠道
 */
@Channel(ChannelTypeEnum.DingtalkApp)
@FieldDefaults(level = AccessLevel.PRIVATE)
@Component
public class DingtalkAppMessageSender extends AbstractMessageSender {
    final String PREFIX_URL = DomainNameEnum.Dingtalk.getUrl();

    @Override
    public String sendMessage(String message, PushChannelAccount account) {
        return run(message, account);
    }

    private String run(String message, PushChannelAccount account) {
        DingtalkAppAccountConfigBo configBo = getConfigBo(account);
        checkAccountConfig(configBo);
        String token = DingtalkUtils.getAccessToken(configBo);
        OapiMessageCorpconversationAsyncsendV2Response rsp = null;
        try {
            DingTalkClient client = new DefaultDingTalkClient(PREFIX_URL + "/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = JSON.parseObject(message, OapiMessageCorpconversationAsyncsendV2Request.class);
            rsp = client.execute(req, token);
        } catch (ApiException e) {
            e.printStackTrace();
            AssertUtils.throwError(e.getMessage());
        }

        if (!rsp.isSuccess()) {
            AssertUtils.throwError(JSON.toJSONString(rsp));
        }
        return rsp.getBody();
    }

    private DingtalkAppAccountConfigBo getConfigBo(PushChannelAccount account) {
        String accountConfig = account.getAccountConfig();
        return JSON.parseObject(accountConfig, DingtalkAppAccountConfigBo.class);
    }

    /**
     * 校验配置
     *
     * @param configBo
     */
    private void checkAccountConfig(DingtalkAppAccountConfigBo configBo) {
        AssertUtils.isNotBlank("appKey 不允许为空！", configBo.getAppKey());
        AssertUtils.isNotBlank("appSecret 不允许为空！", configBo.getAppSecret());
        AssertUtils.isNotNull("agentId 不允许为空！", configBo.getAgentId());
    }
}
